package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AdminPurchaseService;
import org.linlinjava.litemall.admin.util.wxSendMessage;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@RequestMapping("/admin/purchaseManage")
@Validated
public class AdminPurchaseManageController {

    private final Log logger = LogFactory.getLog(AdminGoodsController.class);

    private String status = "2";

    @Autowired
    private AdminPurchaseService adminPurchaseService;

    @Autowired
    private LitemallUserService litemallUserService;

    @Autowired
    private wxSendMessage wxSendMessage;

    @Autowired
    private LitemallPurchaseManageService litemallPurchaseManageService;

    @Autowired
    private LitemallFormPurchaseItemService litemallFormPurchaseItemService;

    @Autowired
    private LitemallPurchaseService litemallPurchaseService;

    @Autowired
    private LitemallQuotePriceService litemallQuotePriceService;


    /**
     * 查询
     *
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:purchaseManage:list")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String sort,
                       String startTime,String endTime,String needHerb,
                       String order, boolean selectAll,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit
    ) {

        return ResponseUtil.okList(adminPurchaseService.list(status,sort,startTime,endTime,needHerb,order,page,limit,selectAll));
    }

    /**
     * 查询报价详情
     *
     * @return
     */
    @RequiresPermissions("admin:purchaseManage/fetchPurchaseAndItemList")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "查询报价详情")
    @GetMapping("/fetchPurchaseAndItemList")
    public Object fetchPurchaseAndItemList(String id,byte type) {
        Map<String,Object> returnMap = new HashMap<String, Object>();
        litemallPurchaseManageService.checkStatus(Integer.valueOf(id));
        LitemallFormPurchase Purchase = adminPurchaseService.selectByPrimaryKey(Integer.valueOf(id));
        returnMap.put("purchase",Purchase);

        List<LitemallFormPurchaseManage> purchaseManage = litemallPurchaseManageService.fetchPurchaseItem(Integer.valueOf(id),type);
        returnMap.put("purchaseManage",purchaseManage);

        return ResponseUtil.ok(returnMap);


    }


    /**
     * 查询供应商详细
     *
     * @return
     */
    @RequiresPermissions("admin:purchaseManage/querySupplierDetails")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "查询供应商详细")
    @GetMapping("/querySupplierDetails")
    public Object querySupplierDetails(String purchaseId,Boolean type,String contactTel) {
        List<LitemallShopAndOffer> purchaseManage = litemallPurchaseManageService.querySupplierDetails(Integer.valueOf(purchaseId),type,contactTel);
        for (LitemallShopAndOffer shopAndOffer:purchaseManage) {
        }
        return ResponseUtil.ok(purchaseManage);
    }

    /**
     * 结束报价
     *
     * @param litemallFormPurchaseItem
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/endQuote")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "结束报价")
    @PostMapping("/endQuote")
    public Object endQuote(@RequestBody List<LitemallFormPurchaseItem> litemallFormPurchaseItem) {
        for (LitemallFormPurchaseItem item:litemallFormPurchaseItem) {
            litemallFormPurchaseItemService.updateStatusAndTime(item.getId(),"1",null);
        }
        return ResponseUtil.ok(litemallFormPurchaseItem);
    }

    /**
     * 查询报价
     *
     * @param purchaseId
     * param contactTel
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/queryQuoteDetails")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "查询报价")
    @GetMapping("/queryQuoteDetails")
    public Object queryQuoteDetails(Integer purchaseId,String contactTel) {
        List<LitemallShopAndOffer> purchaseManage = litemallPurchaseManageService.querySupplierDetails(purchaseId,false,contactTel);
        return ResponseUtil.ok(purchaseManage);
    }

    /**
     * 中标
     *
     * @param litemallFormPurchaseManage
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/winBidding")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "中标")
    @PostMapping("/winBidding")
    public Object winBidding(@RequestBody List<LitemallFormPurchaseManage> litemallFormPurchaseManage) {
        for (LitemallFormPurchaseManage purchaseManage:litemallFormPurchaseManage) {

            litemallFormPurchaseItemService.updateStatusAndTime(purchaseManage.getId(),"2",purchaseManage.getInspectionCompletionTime());
            litemallQuotePriceService.updateStatus(purchaseManage.getPriceId(),"1");
            LitemallUser user = litemallUserService.queryMainByShopId(purchaseManage.getSupplyShopId());
            LitemallFormPurchase purchase = litemallPurchaseService.findById(purchaseManage.getFormPurchaseId());
            wxSendMessage.pushState(user.getWeixinOpenid(),purchase.getShopName(),purchaseManage.getHerbName());
        }
        return ResponseUtil.ok(litemallFormPurchaseManage);
    }

    /**
     * 结束报价
     *
     * @param litemallFormPurchaseManage
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/undo")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "撤销中标")
    @PostMapping("/undo")
    public Object undo(@RequestBody List<LitemallFormPurchaseManage> litemallFormPurchaseManage) {
        for (LitemallFormPurchaseManage purchaseManage:litemallFormPurchaseManage) {
            litemallFormPurchaseItemService.updateStatusAndTime(purchaseManage.getId(),"1",null);
            litemallQuotePriceService.updateStatus(purchaseManage.getPriceId(),"0");
        }
        return ResponseUtil.ok(litemallFormPurchaseManage);
    }

    /**
     * 批量送检
     *
     * @param litemallFormPurchaseManage
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/batchInspection")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "批量送检")
    @PostMapping("/batchInspection")
    public Object batchInspection(@RequestBody List<LitemallFormPurchaseManage> litemallFormPurchaseManage) {
        for (LitemallFormPurchaseManage purchaseManage:litemallFormPurchaseManage) {
            litemallFormPurchaseItemService.updateCheckStatusAndReceivedAmount(purchaseManage.getId(),"1",purchaseManage.getReceivedAmount());
        }
        return ResponseUtil.ok(litemallFormPurchaseManage);
    }

    /**
     * 批量送检
     *
     * @param litemallFormPurchaseManage
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/qualified")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "确认收货")
    @PostMapping("/qualified")
    public Object qualified(@RequestBody List<LitemallFormPurchaseManage> litemallFormPurchaseManage) {
        for (LitemallFormPurchaseManage purchaseManage:litemallFormPurchaseManage) {
            litemallFormPurchaseItemService.updateStatusAndCheckStatusAndReceivedAmount(purchaseManage.getId(),"3","2",purchaseManage.getReceivedAmount());
        }
        return ResponseUtil.ok(litemallFormPurchaseManage);
    }

    /**
     * 批量送检
     *
     * @param litemallFormPurchaseManage
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/noQualified")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "确认退货")
    @PostMapping("/noQualified")
    public Object noQualified(@RequestBody List<LitemallFormPurchaseManage> litemallFormPurchaseManage) {
        for (LitemallFormPurchaseManage purchaseManage:litemallFormPurchaseManage) {
            litemallFormPurchaseItemService.updateStatusAndCheckStatusAndReceivedAmount(purchaseManage.getId(),"3","3", BigDecimal.valueOf(0));
        }
        return ResponseUtil.ok(litemallFormPurchaseManage);
    }

    /**
     * 批量送检
     *
     * @param litemallFormPurchaseManage
     * @return
     */
    @RequiresPermissions("admin:/purchaseManage/uploadAttachments")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "上传附件")
    @PostMapping("/uploadAttachments")
    public Object uploadAttachments(@RequestBody LitemallFormPurchaseManage litemallFormPurchaseManage) {
            litemallFormPurchaseItemService.uploadAttachments(litemallFormPurchaseManage.getId(),litemallFormPurchaseManage.getRemark(),litemallFormPurchaseManage.getRemarkImage());
        return ResponseUtil.ok(litemallFormPurchaseManage);
    }

    /**
     * 新增
     *
     * @param map
     * @return
     */
    @RequiresPermissions("admin:purchaseManage:create")
    @RequiresPermissionsDesc(menu = {"供求信息", "采购信息管理"}, button = "二次发布")
    @PostMapping("/create")
    public Object create(@RequestBody Map<String,Object> map) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LinkedHashMap<String,?> dataForm = (LinkedHashMap<String, String>) map.get("dataForm");
        List<LinkedHashMap<String,?>> herbList= (List<LinkedHashMap<String, ?>>) map.get("herbList");

        LitemallFormPurchase purchase = new LitemallFormPurchase();
        purchase.setParentId(Integer.valueOf(dataForm.get("id").toString()));
        purchase.setName(dataForm.get("name").toString());
        purchase.setAddressId(Integer.parseInt(dataForm.get("addressId").toString()));
        purchase.setStatus(Byte.parseByte(dataForm.get("status").toString()));
        purchase.setInventoryPlace(dataForm.get("inventoryplace").toString());
        purchase.setDueTime(LocalDateTime.parse(dataForm.get("dueTime").toString(), formatter));
        purchase.setContactName(dataForm.get("contactName").toString());
        purchase.setContactTel(dataForm.get("contactTel").toString());
        for (LinkedHashMap<String,?> herbMap:herbList) {
            if (!StringUtils.isEmpty(purchase.getNeedHerb())){
                purchase.setNeedHerb(
                        purchase.getNeedHerb()+","+
                                herbMap.get("herbName").toString()+herbMap.get("specifications").toString()+" "+
                                (new BigDecimal(herbMap.get("needAmount").toString()).subtract(new BigDecimal(herbMap.get("receivedAmount").toString()))).toString()+
                                herbMap.get("measurementUnit").toString()
                );
            }else {
                purchase.setNeedHerb(
                                herbMap.get("herbName").toString()+herbMap.get("specifications").toString()+" "+
                                (new BigDecimal(herbMap.get("needAmount").toString()).subtract(new BigDecimal(herbMap.get("receivedAmount").toString()))).toString()+
                                herbMap.get("measurementUnit").toString()
                );
            }

        }
        purchase = adminPurchaseService.add(purchase);


        List<LitemallFormPurchaseItem> ItemList= new ArrayList<>();
        for (LinkedHashMap<String,?> herbMap:herbList) {
            LitemallFormPurchaseItem purchaseItem = new LitemallFormPurchaseItem();
            purchaseItem.setFormPurchaseId(purchase.getId());
            purchaseItem.setHerbId(Integer.valueOf(herbMap.get("herbId").toString()));
            purchaseItem.setCode(herbMap.get("code").toString());
            purchaseItem.setHerbName(herbMap.get("herbName").toString());
            purchaseItem.setMeasurementUnit(herbMap.get("measurementUnit").toString());
            purchaseItem.setSpecifications(herbMap.get("specifications").toString());
            purchaseItem.setNeedAmount(new BigDecimal(herbMap.get("needAmount").toString()).subtract(new BigDecimal(herbMap.get("receivedAmount").toString())));
            purchaseItem.setReceivedAmount(purchaseItem.getNeedAmount());
            purchaseItem.setStatus("0");
            purchaseItem.setCheckStatus("0");
            ItemList.add(purchaseItem);
        }
        litemallFormPurchaseItemService.batchInsert(ItemList);

        return ResponseUtil.ok(map);
    }



}
